package com.xirui.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xirui.bean.Middle;
import com.xirui.bean.Paymaster;
import com.xirui.bean.Roll;
import com.xirui.bean.Structure;
import com.xirui.mapper.RollMapper;
import com.xirui.service.RollService;

@Service
public class RollServiceImpl implements RollService{

	
	@Autowired
	private RollMapper rollMapper;

	public PageInfo<Roll> selectRoll(Integer pageNum, Roll roll) {
		PageHelper.startPage(pageNum, 3);
		List<Roll> list=rollMapper.selectRoll(roll);
		return new PageInfo<Roll>(list);
	}

	public int deleteRoll(Integer id) {
		
		return rollMapper.deleteRoll(id);
	}

	public List<Structure> sanji(Integer id) {
		
		return rollMapper.sanji(id);
	}

	public void addRoll(Roll roll, MultipartFile file) throws IllegalStateException, IOException {
		if(file!=null && file.getSize()>0){
			String fileName=UUID.randomUUID().toString()+file.getOriginalFilename();
			File file2 = new File("C:/HG",fileName);
			file.transferTo(file2);
			roll.setBills("/HG/"+fileName);
		}
		roll.setCretime(new Date());
		rollMapper.addRoll(roll);
		List<Paymaster> paymasters = roll.getPaymasters();
		for (Paymaster paymaster : paymasters) {
			rollMapper.addPay(paymaster); 	
			rollMapper.addMiddle(roll.getId(),paymaster.getId());
		}
		
	}

	public List<Paymaster> selRoll(Integer id) {
		List<Paymaster> list= new ArrayList<Paymaster>();
		Roll roll=rollMapper.selRoll1(id);
		List<Middle> middle=rollMapper.selMiddle(roll.getId());
		for (Middle middle2 : middle) {
			Paymaster pay=rollMapper.selPay(middle2.getUid());
			list.add(pay);
		}
		for (Paymaster p : list) {
			System.out.println(p);
		}
		return list;
	}

	
	
	public void updateRoll(Roll roll, MultipartFile file) {
		try {
			
			if(file!=null && file.getSize()>0){
				String fileName=UUID.randomUUID().toString()+file.getOriginalFilename();
				File file2 = new File("C:/HG",fileName);
				file.transferTo(file2);
				roll.setBills("/HG/"+fileName);
			}
			roll.setCretime(new Date());
			rollMapper.updateRoll(roll);
			rollMapper.deleteMiddle(roll.getId());
			List<Paymaster> paymasters = roll.getPaymasters();
			for (Paymaster paymaster : paymasters) {
				rollMapper.addPay(paymaster); 	
				rollMapper.addMiddle(roll.getId(),paymaster.getId());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}


	
	
}
